<?php
include 'class.database.php';
function select_image($id){
		$query = mysql_query("SELECT image FROM user WHERE id ='".$id."'") or die(mysql_error());
		$result = mysql_fetch_array($query);
		return $result['image'];
	}

function delete_image($id){		
		$query_del = mysql_query("DELETE FROM files WHERE id='".$id."'") or die(mysql_error());
		if (mysql_query ("UPDATE user SET image = '0' WHERE id ='".$id."'"))	
			return true;
		return false;
	}
	
function image($id){
		$query = mysql_query("SELECT * FROM files WHERE id ='".$id."'") or die(mysql_error());
		$result = mysql_fetch_array($query);
		$html = '../';
		$html .= $result['url'];
		$html .= $result['name'];
		return $html;
	}
	
session_start();
$select = select_image($_SESSION['user']['id']);
if ($select != 0){		
	unlink(image($select));	
	$result = delete_image($select);	
}

$uploaddir = '../images/uploads/';

$res['name'] = $_FILES["myfile"]["name"] = md5($_FILES["myfile"]["name"].time()).'.jpg';

$res['size'] = $_FILES['myfile']['size'];
$res['type'] = $_FILES['myfile']['type'];
$uploadfile = $uploaddir.$_FILES['myfile']['name'];

mysql_query("INSERT INTO files (name, url, size, mime) VALUES ('".$res['name']."', 'images/uploads/', '".$res['size']."', '".$res['type']."')");

$query = mysql_query("SELECT * FROM files WHERE name='".$res['name']."'");
$res_query = mysql_fetch_array($query);
$id_file = $res_query['id'];
mysql_query ("UPDATE user SET image = '".$id_file."' WHERE id ='".$_SESSION['user']['id']."'");	

move_uploaded_file($_FILES['myfile']['tmp_name'], $uploadfile);
	

$filename = $uploadfile;
 
list($width, $height,$type) = getimagesize($filename);
if ($type==IMAGETYPE_JPEG){
	$new_width = 200;
	$i = $width/200;
	$new_height = $height/$i;	 
	 
	$image_p = imagecreatetruecolor($new_width, $new_height);
	$image = imagecreatefromjpeg($filename);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
	 
	imagejpeg($image_p, '../images/uploads/'.$res['name'],50);
	$atr = $res['name'];
	return print json_encode($atr);
}
elseif ($type==IMAGETYPE_GIF){
	$new_width = 200;
	$i = $width/200;
	$new_height = $height/$i;	 
	 
	$image_p = imagecreatetruecolor($new_width, $new_height);
	$image = imagecreatefromgif($filename);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
	 
	imagejpeg($image_p, '../images/uploads/'.$res['name'],50);
	$atr = $res['name'];
	return print json_encode($atr);
}
elseif ($type==IMAGETYPE_PNG){
	$new_width = 200;
	$i = $width/200;
	$new_height = $height/$i;	 
	 
	$image_p = imagecreatetruecolor($new_width, $new_height);
	$image = imagecreatefrompng($filename);
	imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
	 
	imagejpeg($image_p, '../images/uploads/'.$res['name'],50);
	$atr = $res['name'];
	return print json_encode($atr);
}
return false;
?>